package com.settlement.system.controller;

import com.settlement.system.common.enums.ChannelEnum;
import com.settlement.system.common.exception.ServiceException;
import com.settlement.system.common.annotation.LoggerProfile;
import com.settlement.system.model.entity.common.*;
import com.settlement.system.model.param.TblAdvertiseMarketAccountApiResponseParams;
import com.settlement.system.reply.ListResponse;
import com.settlement.system.reply.ObjectDataResponse;
import com.settlement.system.service.IBaseService;
import com.settlement.system.service.ITblAdvertiseMarketAccountService;
import com.settlement.system.service.ITblRrChannelService;
import com.settlement.system.common.util.common.FasUtil;
import com.settlement.system.common.util.common.JsonUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.fastjson2.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import jakarta.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 广告营销账户信息表 前端控制器
 * @author xiaochuan
 * @since 2021-01-27
 */

@Slf4j
@Api(tags = "广告营销账户信息表",description = "广告营销账户信息表")
@RestController
@RequestMapping("/tblAdvertiseMarketAccount")
public class TblAdvertiseMarketAccountController extends MergeApiExcelController<TblAdvertiseMarketAccount, Map<String, Object>> {

    @Resource
    private ITblAdvertiseMarketAccountService tblAdvertiseMarketAccountService;

    @Resource
    private ITblRrChannelService tblRrChannelService;

    @Override
    public IBaseService init() {
        return tblAdvertiseMarketAccountService;
    }

    @Override
    public Class<?> getModelClass() {
        return TblAdvertiseMarketAccount.class;
    }

    @Override
    protected void setParamsModel(Map<String, Object> model) {
        FasUtil.formatInQueryCondition(model, "ncShopNo", "loginAccount", "channelNo", "channelName", "loginPassword", "ncShopName", "shopAccountName");
        super.setParamsModel(model);
    }

    @Override
    protected void setFootModel(Map<String, Object> result, Map<String, Object> model) throws ServiceException {
        TblAdvertiseMarketAccount foot = tblAdvertiseMarketAccountService.getFoot(model);
        result.put("foot", foot==null? getModelClass():foot);
    }

    @Override
    protected String verifyData(List<TblAdvertiseMarketAccount> list) {
        for (TblAdvertiseMarketAccount detail : list) {
            String message = verify(detail);
            if (!StringUtils.isEmpty(message)) {
                return message;
            }
        }
        return super.verifyData(list);
    }

    /**
     * 验证数据
     *
     * @param detail
     * @return
     */
    private String verify(TblAdvertiseMarketAccount detail) {
        if (ChannelEnum.TM.getName().equals(detail.getChannelName()) && StringUtils.isBlank(detail.getPhone())) {
            return JsonUtil.getJsonOrToString(detail) + ":渠道是天猫时，电话不能为空";
        }
        if(StringUtils.isEmpty(detail.getNeedDownReport())){
            detail.setNeedDownReport("2");
        }

        if(!detail.getNeedDownReport().equals("1") && !detail.getNeedDownReport().equals("2")){
            return "是否需要下载报表字段取值范围：需要、不需要";
        }

        return null;
    }

    @Override
    public String verifyImportObject(TblAdvertiseMarketAccount detail, AnalysisContext analysisContext) {

        String message = super.verifyImportObject(detail,analysisContext);
        if(StringUtils.isNotEmpty(message)){
            return message;
        }
        detail.setNcShopNo(detail.getNcShopNo().replace("：",":"));
        if(StringUtils.isEmpty(detail.getNeedDownReport())){
            detail.setNeedDownReport("2");
        }

        if(!detail.getNeedDownReport().equals("1") && !detail.getNeedDownReport().equals("2")){
            return "是否需要下载报表字段取值范围：需要、不需要";
        }

        if (ChannelEnum.TM.getName().equals(detail.getChannelName()) && StringUtils.isBlank(detail.getPhone())) {
            return "渠道是天猫时，电话不能为空";
        }
        Map params = JSON.parseObject(JSON.toJSONString(detail), Map.class);
        try {
            Map<String,Object> params1 = new HashMap<String,Object>(16);
            params1.put("ncShopNo",detail.getNcShopNo());
            setParamsModel(params1);
            List list = tblAdvertiseMarketAccountService.selectByParam(params1);
            if(list!=null && !list.isEmpty()){
                return "数据重复，NC_SHOP_NO "+detail.getNcShopNo() + "已存在";
            }

            params.put("checkPhone","checkPhone");
            setParamsModel(params);
            list = tblAdvertiseMarketAccountService.selectByParam(params);
            if(list!=null && !list.isEmpty()){
                return "数据重复";
            }

            String channelName = detail.getChannelName();
            if(StringUtils.isNotBlank(channelName)){
                String noByName = tblRrChannelService.getNoByName(channelName);
                if(StringUtils.isEmpty(noByName)){
                    return "渠道未设置";
                }
                detail.setChannelNo(noByName);
            }

        } catch (ServiceException e) {
            e.printStackTrace();
            return "校验时查询出错";
        }

        return null;
    }

    @Override
    protected void saveData(List<TblAdvertiseMarketAccount> datas) throws ServiceException {
        List<String> ncShopNoList = new ArrayList<>();
        for(TblAdvertiseMarketAccount account : datas){
            if(ncShopNoList.contains(account.getNcShopNo())){
                throw new ServiceException("有两行的NC_SHOP_NO"+account.getNcShopNo()+"重复");
            }else{
                ncShopNoList.add(account.getNcShopNo());
            }
        }

        super.saveData(datas);
    }

    /**
     * 获取
     *
     * @return
     */
    @ApiOperation(value = "获取列表")
    @LoggerProfile(methodNote="获取列表")
    @RequestMapping(value = "/api/list", method = RequestMethod.POST)
    public ObjectDataResponse<ListResponse<TblAdvertiseMarketAccountApiResponseParams>> list(@RequestBody BasePager<Map<String, Object>> model) {
        ListResponse<TblAdvertiseMarketAccountApiResponseParams> result = new ListResponse<>();
        try {
            Map<String, Object> params = getRequestParam(model);
            setParamsModel(params);
            int count = baseService.selectCount(params);
            List<TblAdvertiseMarketAccountApiResponseParams> rows =
                    new ArrayList<>();
            List<TblAdvertiseMarketAccount> tasks = baseService.selectByPage(new SinglePage(model), params,
                    "id", "ASC");
            tasks.forEach(task->{
                BeanMap beanMap = new BeanMap(task);
                TblAdvertiseMarketAccountApiResponseParams responseParams =
                        JSON.parseObject(JSON.toJSONString(beanMap), TblAdvertiseMarketAccountApiResponseParams.class);
                rows.add(responseParams);
            });
            result.setTotal(count);
            result.setRows(rows);
        } catch (Exception ex) {
            log.error("获取列表出错", ex);
            return new ObjectDataResponse(500, "服务器异常");
        }
        return new ObjectDataResponse<ListResponse<TblAdvertiseMarketAccountApiResponseParams>>(result, 200, "success");
    }
}

